﻿using System;
using System.IO;
using System.Net;
using DMS.BaseClass;
using DMS.Business.Utility;

namespace DMS.Business.Utility
{
    public class FileTruck
    {
        private static FileUploader uploader = new FileUploader(AppParams.FileServer
                                                              , AppParams.FileServerAccount
                                                              , AppParams.FileServerPassword);

        #region 公共方法

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filePath">文件路径(包括文件名)</param>
        /// <param name="stream">文件字符串</param>
        /// <returns></returns>
        public static string UploadFile(string filePath, Stream stream)
        {
            string fileUrl = uploader.GetFileUrl(filePath);
            uploader.PrepareWebDirectory(fileUrl);
            if (uploader.WebFileDirectoryExist(fileUrl))
            {
                FileTruck.DeleteFile(filePath);
            }
            uploader.UploadFileWithoutPrepareDirectory(stream, fileUrl);
            return fileUrl;
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件路径(包括文件名)</param>
        public static void DeleteFile(string filePath)
        {
            string targetUrl = uploader.GetFileUrl(filePath);
            uploader.WebDavOperate(targetUrl, "DELETE");
        }
        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="filePath">文件路径(包括文件名)</param>
        /// <returns></returns>
        public static bool Exists(string filePath)
        {
            string fileUrl = uploader.GetFileUrl(filePath);
            uploader.PrepareWebDirectory(fileUrl);
            return uploader.WebFileDirectoryExist(fileUrl);
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath">文件路径(包括文件名)</param>
        /// <returns></returns>
        public static Stream DownloadFile(string filePath)
        {
            Uri requestUri =  new Uri(uploader.GetFileUrl(filePath));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            LogHelper.LogAction2("Download File", "requestUri:"+requestUri);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return response.GetResponseStream();
        }
        #endregion



    }
}
